package com.arvin.controller;

import com.arvin.pojo.*;
import com.arvin.service.AdminService;
import com.arvin.service.LogService;
import com.arvin.utils.JwtUtil;
import com.arvin.utils.Md5Util;
import com.arvin.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@Tag(name = "管理端接口",description = "管理端接口")
@Slf4j
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private LogService logService;

    /**
     * 管理员登录
     * @param admin
     * @return
     */
    @Operation(summary = "管理员登录",description = "管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        String username = admin.getUsername();
        String password = admin.getPassword();
        //通过用户名查找
        Admin adminLogin = adminService.findByUsername(username);
        log.info(username);
        //判断是否存在
        if (adminLogin == null) {
            return Result.error("管理员不存在");
        }
        if (adminLogin.getBan() == 1) {
            if (Md5Util.getMD5String(password).equals(adminLogin.getPassword())) {
                //用户名密码匹配登陆成功
                //jWT令牌获取
                Map<String, Object> claims = new HashMap<>();
                claims.put("username", adminLogin.getUsername());
                String token = JwtUtil.genToken(claims);
                return Result.success(token);
            } return Result.error("密码错误");
        }
       return Result.error("账号已被禁用，请联系超级管理员");
    }

    /**
     * 添加管理员
     * @param admin
     * @return
     */
    @Operation(summary = "添加管理员",description = "添加管理员")
    @PostMapping("/addAdmin")
    public Result addAdmin(@RequestBody Admin admin) {
        //查询管理员是否已存在,通过ThreadLocalUtil获取登陆时的username,添加管理员
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Admin admin1 = adminService.findByUsername(username);
        if (admin1.getSuperSign() == 1) {
            Admin adminLogin = adminService.findByUsername(admin.getUsername());
            if (adminLogin == null&&admin.getPassword() != null) {
                // 添加日志
                Log log = new Log();
                log.setUsername(username);
                log.setLogType("管理员");
                log.setLogOperate("管理员" + username + "新增管理员账号" + admin.getUsername());
                log.setLogTime(LocalDateTime.now());
                logService.insert(log);

                adminService.addAdmin(admin);
                return Result.success();
            }
            if (adminLogin != null) {
                return Result.error("管理员已存在");
            }
        }
        return Result.error("权限不够，请联系超级管理员");
    }

    /**
     * 修改密码
     * @param admin
     * @return
     */
    @Operation(summary = "修改密码",description = "修改密码")
    @PostMapping("/changePassword")
    private Result changePassword(@RequestBody Admin admin){
        if (!StringUtils.hasLength(admin.getPassword()) || !StringUtils.hasLength(admin.getNewPassword()) || !StringUtils.hasLength(admin.getConfirmPassword())) {
            return Result.error("缺少必要的参数");
        }
        Map<String,Object> map =ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Admin loginadmin = adminService.findByUsername(username);
        if (!loginadmin.getPassword().equals(Md5Util.getMD5String(admin.getPassword()))){
            return Result.error("原密码填写不正确");
        }
        if (!admin.getNewPassword().equals(admin.getConfirmPassword())) {
            return Result.error("两次密码填写不一样");
        }
        // 添加日志
        Log log = new Log();
        log.setUsername(username);
        log.setLogType("管理员");
        log.setLogOperate("管理员" + username + "修改了密码");
        log.setLogTime(LocalDateTime.now());
        logService.insert(log);

        adminService.updatePassword(admin.getNewPassword(),loginadmin.getUsername());
        return Result.success();

    }

    /**
     * 获取管理员信息列表
     * @param username
     * @return
     */
    @Operation(summary = "获取管理员信息列表",description = "获取管理员信息列表")
    @GetMapping("/getAdminInfo")
    public Result<List<Admin>> getAdminInfoList(String username){
        List<Admin> adminInfoList = adminService.getAdminInfoList(username);
        return Result.success(adminInfoList);
    }

    /**
     * 更新管理员信息
     * @param admin
     * @return
     */
    @Operation(summary = "更新管理员信息",description = "更新管理员信息")
    @PostMapping("/updateAdminInfo")
    public Result updateAdminInfo(@RequestBody Admin admin){
        Map<String,Object> map =ThreadLocalUtil.get();
        String username = (String) map.get("username");
        Admin loginadmin = adminService.findByUsername(username);
        if (StringUtils.hasLength(admin.getPassword())){
            if (!admin.getPassword().equals(admin.getConfirmPassword())) {
                return Result.error("两次密码填写不一样");
            }
        }
        if (loginadmin.getSuperSign() == 1) {
            // 添加日志
            Log log = new Log();
            log.setUsername(username);
            log.setLogType("管理员");
            log.setLogOperate("管理员" + username + "修改了管理员账号" + admin.getUsername());
            log.setLogTime(LocalDateTime.now());
            logService.insert(log);

            adminService.updateAdminInfo(admin);
            return Result.success();
        }
        return Result.error("权限不够，请联系超级管理员");
    }

    /**
     * 删除管理员信息
     * @param username
     * @return
     */
    @Operation(summary = "删除管理员信息",description = "删除管理员信息")
    @GetMapping("/deleteAdminInfo")
    public Result deleteAdminInfo(String username){
        Map<String,Object> map =ThreadLocalUtil.get();
        String username1 = (String) map.get("username");
        Admin loginadmin = adminService.findByUsername(username1);
        if (loginadmin.getSuperSign() == 1) {
            // 添加日志
            Log log = new Log();
            log.setUsername(username);
            log.setLogType("管理员");
            log.setLogOperate("管理员" + username1 + "删除了管理员账号" + username);
            log.setLogTime(LocalDateTime.now());
            logService.insert(log);

            adminService.deleteAdminInfo(username);
            return Result.success();
        }
        return Result.error("权限不够，请联系超级管理员");
    }

    /**
     * 获取入班人员
     * @param page
     * @param pageSize
     * @param studentId
     * @param stuName
     * @param className
     * @return
     */
    @Operation(summary = "获取入班人员",description = "获取入班人员")
    @GetMapping("/getEnterClassInfo")
    public Result<PageBean> getEnterClassInfo(Integer page, Integer pageSize, String studentId, String stuName,String className){
        PageBean pageBean = adminService.getEnterClassInfo(page, pageSize, studentId, stuName,className);
        log.info("入班学生信息{}", pageBean);
        return Result.success(pageBean);
    }

    /**
     * 退班
     * @param studentId
     * @return
     */
    @Operation(summary = "退班",description = "删除所有信息学生信息")
    @DeleteMapping("/deleteStudent/{studentId}")
    public Result deleteStudent(@PathVariable String studentId){
        Map<String,Object> map =ThreadLocalUtil.get();
        String username = (String) map.get("username");
        // 添加日志
        Log log = new Log();
        log.setUsername(username);
        log.setLogType("卓越班");
        log.setLogOperate("管理员" + username + "将学号为" + studentId + "的学生请出了卓越班");
        log.setLogTime(LocalDateTime.now());
        logService.insert(log);

        adminService.deleteStudent(studentId);
        return Result.success();
    }
}
